

import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import styles from './styles.module.css';

interface CourseData {
  name: string;
  instructor: string;
  price: string;
  cover: string;
}

const EnrollConfirmPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string | null>(null);
  const [courseData, setCourseData] = useState<CourseData>({
    name: 'Python编程基础',
    instructor: '李教授',
    price: '¥299',
    cover: 'https://s.coze.cn/image/J0SAtBW4SFA/'
  });

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '确认订单 - 学途';
    return () => { document.title = originalTitle; };
  }, []);

  // 根据URL参数加载课程信息
  useEffect(() => {
    const courseId = searchParams.get('courseId');
    
    const courseDataMap: Record<string, CourseData> = {
      'course1': {
        name: 'Python编程基础',
        instructor: '李教授',
        price: '¥299',
        cover: 'https://s.coze.cn/image/1r9WpFs1h20/'
      },
      'course2': {
        name: '数据分析与可视化',
        instructor: '王老师',
        price: '¥399',
        cover: 'https://s.coze.cn/image/X8yTiMqzkJQ/'
      },
      'course3': {
        name: '项目管理实战',
        instructor: '张经理',
        price: '¥499',
        cover: 'https://s.coze.cn/image/bDQe5L2bylg/'
      }
    };

    if (courseId && courseDataMap[courseId]) {
      setCourseData(courseDataMap[courseId]);
    }
  }, [searchParams]);

  // 处理支付方式选择
  const handlePaymentMethodSelect = (method: string) => {
    setSelectedPaymentMethod(method);
  };

  // 处理去支付
  const handlePay = () => {
    if (!selectedPaymentMethod) {
      alert('请选择支付方式');
      return;
    }

    const courseId = searchParams.get('courseId') || 'course1';
    
    // 模拟跳转到支付页面
    console.log('跳转到支付页面', {
      paymentMethod: selectedPaymentMethod,
      courseId: courseId,
      courseName: courseData.name,
      amount: courseData.price
    });

    // 显示支付成功提示
    alert(`正在跳转到${selectedPaymentMethod === 'wechat' ? '微信' : '支付宝'}支付页面...`);

    // 模拟支付成功后跳转回课程详情页
    setTimeout(() => {
      navigate(`/course-detail?courseId=${courseId}&enrolled=true`);
    }, 2000);
  };

  // 处理取消
  const handleCancel = () => {
    const courseId = searchParams.get('courseId') || 'course1';
    navigate(`/course-detail?courseId=${courseId}`);
  };

  // 处理关闭弹窗
  const handleCloseModal = () => {
    const courseId = searchParams.get('courseId') || 'course1';
    navigate(`/course-detail?courseId=${courseId}`);
  };

  // 处理背景点击
  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (e.target === e.currentTarget) {
      handleCloseModal();
    }
  };

  // 处理ESC键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        handleCloseModal();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  // Tab键导航支持
  useEffect(() => {
    const focusableElements = document.querySelectorAll('button, .payment-method-option');
    let currentFocus = -1;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Tab') {
        e.preventDefault();
        
        if (e.shiftKey) {
          // Shift + Tab
          currentFocus = currentFocus > 0 ? currentFocus - 1 : focusableElements.length - 1;
        } else {
          // Tab
          currentFocus = currentFocus < focusableElements.length - 1 ? currentFocus + 1 : 0;
        }
        
        if (focusableElements[currentFocus]) {
          focusableElements[currentFocus].focus();
        }
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    
    // 初始化焦点
    if (focusableElements.length > 0) {
      focusableElements[0].focus();
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  return (
    <div className={styles.pageWrapper}>
      {/* 模态弹窗背景 */}
      <div 
        className={`fixed inset-0 ${styles.modalBackdrop} flex items-center justify-center z-50 p-4`}
        onClick={handleBackdropClick}
      >
        {/* 模态弹窗内容 */}
        <div className={`bg-white rounded-xl shadow-modal w-full max-w-md ${styles.fadeIn}`}>
          {/* 弹窗头部 */}
          <div className="flex items-center justify-between p-6 border-b border-border-light">
            <h2 className="text-xl font-semibold text-text-primary">确认订单</h2>
            <button 
              onClick={handleCloseModal}
              className="text-text-secondary hover:text-text-primary transition-colors"
            >
              <i className="fas fa-times text-lg"></i>
            </button>
          </div>
          
          {/* 弹窗内容 */}
          <div className="p-6">
            {/* 课程信息 */}
            <div className="mb-6">
              <div className="flex items-center space-x-4 mb-4">
                <img 
                  src={courseData.cover}
                  alt={`${courseData.name}课程封面`}
                  className="w-16 h-16 rounded-lg object-cover"
                />
                <div className="flex-1">
                  <h3 className="font-semibold text-text-primary mb-1">{courseData.name}</h3>
                  <p className="text-text-secondary text-sm">{courseData.instructor}</p>
                </div>
              </div>
            </div>
            
            {/* 价格信息 */}
            <div className="mb-6 p-4 bg-bg-light rounded-lg">
              <div className="flex justify-between items-center mb-2">
                <span className="text-text-secondary">课程价格</span>
                <span className="font-semibold text-text-primary">{courseData.price}</span>
              </div>
              <div className="border-t border-border-light pt-2">
                <div className="flex justify-between items-center">
                  <span className="font-medium text-text-primary">总价</span>
                  <span className="text-xl font-bold text-primary">{courseData.price}</span>
                </div>
              </div>
            </div>
            
            {/* 支付方式选择 */}
            <div className="mb-6">
              <h4 className="font-medium text-text-primary mb-3">选择支付方式</h4>
              <div className="space-y-3">
                {/* 微信支付 */}
                <div 
                  className={`${styles.paymentMethodOption} p-4 border border-border-light rounded-lg cursor-pointer ${
                    selectedPaymentMethod === 'wechat' ? styles.paymentMethodSelected : ''
                  }`}
                  onClick={() => handlePaymentMethodSelect('wechat')}
                >
                  <div className="flex items-center space-x-3">
                    <div className={`${styles.radioIndicator} w-4 h-4 border-2 border-gray-300 rounded-full flex items-center justify-center ${
                      selectedPaymentMethod === 'wechat' ? styles.radioIndicatorSelected : ''
                    }`}>
                      <div className={`w-2 h-2 bg-white rounded-full ${
                        selectedPaymentMethod === 'wechat' ? '' : 'hidden'
                      } ${styles.radioDot}`}></div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <i className="fab fa-weixin text-success text-2xl"></i>
                      <span className="font-medium text-text-primary">微信支付</span>
                    </div>
                  </div>
                </div>
                
                {/* 支付宝支付 */}
                <div 
                  className={`${styles.paymentMethodOption} p-4 border border-border-light rounded-lg cursor-pointer ${
                    selectedPaymentMethod === 'alipay' ? styles.paymentMethodSelected : ''
                  }`}
                  onClick={() => handlePaymentMethodSelect('alipay')}
                >
                  <div className="flex items-center space-x-3">
                    <div className={`${styles.radioIndicator} w-4 h-4 border-2 border-gray-300 rounded-full flex items-center justify-center ${
                      selectedPaymentMethod === 'alipay' ? styles.radioIndicatorSelected : ''
                    }`}>
                      <div className={`w-2 h-2 bg-white rounded-full ${
                        selectedPaymentMethod === 'alipay' ? '' : 'hidden'
                      } ${styles.radioDot}`}></div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <i className="fab fa-alipay text-info text-2xl"></i>
                      <span className="font-medium text-text-primary">支付宝支付</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          {/* 弹窗底部 */}
          <div className="flex items-center justify-end space-x-3 p-6 border-t border-border-light bg-bg-light rounded-b-xl">
            <button 
              onClick={handleCancel}
              className="px-6 py-2 border border-border-light text-text-secondary rounded-lg hover:bg-white transition-colors"
            >
              取消
            </button>
            <button 
              onClick={handlePay}
              disabled={!selectedPaymentMethod}
              className="px-6 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed"
            >
              去支付
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EnrollConfirmPage;

